import { FunctionComponent, useCallback, useEffect, useState, useMemo } from 'react';
import { Modal, Checkbox } from 'antd';
import { TextWidget, getMessage } from '@inbiz/react';
import {
  fileschemaOptions,
  folderSchemaOptions,
  metaTransformToSchema,
  SchemaOption,
} from '../../../../designer/conditionsSchema';
import { getMetaTypeList } from '../../../../designer/service';
import { usePrefixClassName } from '../../../../store/hooks/usePrefixClassName';
import useSecretlevel from '../commonUtils/useSecretLevel'
interface Props {
  visible: boolean;
  value?: SchemaOption[];
  onSave?: (schema: any[]) => void;
  onChange?: (schema: any[]) => void;
  onCancel?: () => void;
  type: string;
}

type IMetaTypeList = {
  TypeId: string;
  TypeName: string;
  MetaAttrList: {
    AttrId: string;
    AttrName: string;
    ControlModel: {
      ControlType: string;
    };
  }[];
}[];

// 更多条件弹窗
const MoreConditions: FunctionComponent<Props> = (props) => {
  const { value, visible, type, onCancel, onChange } = props;
  // 所有分类
  const [dataSource, $dataSource] = useState<
    {
      title: string;
      data: {
        label: string;
        key: string;
      }[];
      key: string;
      checked?: boolean;
    }[]
  >([]);
  // 选中分类下的详情
  const dataSourceSelect = useMemo(() => {
    return dataSource.find((item) => item.checked);
  }, [dataSource]);
  const newfileschemaOptions = useSecretlevel({options: fileschemaOptions})
  
  const handleSourceClick = useCallback((key) => {
    $dataSource((list) => {
      return list.map((item) => {
        return {
          ...item,
          checked: item.key === key,
        };
      });
    });
  }, []);

  const [selectMeta, setSelectMeta] = useState<SchemaOption[]>(value || []);
  useEffect(() => {
    setSelectMeta(value || []);
  }, [value]);

  const handleChangeSelect = useCallback((e, data) => {
    let isCheck = e.target.checked;
    let val = data.key as string;
    let schema = data;
    if (val.includes('@') && isCheck) {
      schema = metaTransformToSchema(data, data.typeId);
      if (!schema) {
        return;
      }
    }
    setSelectMeta((prev) => {
      const next = [...prev];
      if (!isCheck) {
        const index = next.findIndex((item) => item.key === val);
        if (index !== -1) {
          next.splice(index, 1);
        }
      } else {
        next.push(schema);
      }
      return next;
    });
  }, []);

  useEffect(() => {
    // 获取元数据类别
    if (visible) {
      $dataSource([
        {
          title: 'SearchEngine.basicInfo',
          key: 'basicInfo_' + type,
          data: Number(type) === 1 ? newfileschemaOptions : folderSchemaOptions,
          checked: true,
        },
      ]);
      getList();
    }
  }, [visible]);

  const getList = async () => {
    await getMetaTypeList().then((res) => {
      if (res.isSucceed && res.result?.length) {
        const list = res.result.map((item: { TypeName: any; TypeId: any; MetaAttrList: any }) => {
          const data = {
            ...item,
            title: item.TypeName,
            key: item.TypeId,
            data: item.MetaAttrList,
          };
          delete data.MetaAttrList;
          data.data = data.data.filter(
            (meta: {
              label: any;
              AttrName: any;
              key: string;
              AttrId: any;
              typeId: any;
              ControlModel: { ControlType: string };
            }) => {
              meta.label = meta.AttrName;
              meta.key = `${item.TypeId}@${meta.AttrId}`;
              meta.typeId = item.TypeId;
              return meta.ControlModel.ControlType != 'edoc2Hidden';
            },
          );
          return data;
        });
        $dataSource((old) => [...old, ...list]);
      }
    });
  };

  // 保存事件
  const handleOk = () => {
    onChange?.([...selectMeta]);
    onCancel && onCancel();
  };

  // 取消事件
  const handleCancel = () => {
    onCancel && onCancel();
  };

  const pfxClassName = usePrefixClassName();

  return (
    <Modal
      title={getMessage('SearchEngine.addRule')}
      visible={visible}
      onOk={handleOk}
      zIndex={1001}
      width={600}
      onCancel={handleCancel}
      cancelText={getMessage('SearchEngine.cancel')}
      okText={getMessage('SearchEngine.confirm')}
    >
      <div className={`${pfxClassName}-more-condition-container`}>
        <div className="left">
          {dataSource.map((item) => {
            return (
              <div
                onClick={() => handleSourceClick(item.key)}
                className={`condition-item extra ${item.checked ? 'selected' : ''}`}
                key={item.key}
              >
                <TextWidget>{item.title}</TextWidget>
              </div>
            );
          })}
        </div>
        <div className="right">
          {dataSourceSelect?.data?.map((item) => {
            return (
              <div key={item.key} className={`condition-item`}>
                <Checkbox
                  defaultChecked={selectMeta.some((s) => s.key === item.key)}
                  key={item.key}
                  onChange={(e) => handleChangeSelect(e, item)}
                >
                  <TextWidget>{item.label}</TextWidget>
                </Checkbox>
              </div>
            );
          })}
        </div>
      </div>
    </Modal>
  );
};

export default MoreConditions;
